package jwei.apps.zappos;

import java.net.URI;
import java.util.List;

import jwei.apps.helpers.ConnectionManager;
import jwei.apps.helpers.GetMethods;
import jwei.apps.json.JsonToStyle;
import jwei.apps.objects.APIConstants;
import jwei.apps.objects.Style;

import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ZapposSearch {

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<Style> searchTerm(String term) {
        String url = String.format(APIConstants.SEARCH, term);
        // chop off http:
        url = url.substring(5, url.length());
        URI uri;
        try {
            uri = new URI("http", url, null);
            url = uri.toURL().toString();
            String response = GetMethods.doGetWithResponse(url, httpClient);
            if (!response.equals("")) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    JSONArray searchResults = jsonResponse.getJSONArray("results");
                    List<Style> ret = JsonToStyle.convertToStyles(searchResults);
                    return ret;
                } catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                System.out.println(ZapposSearch.class.getCanonicalName() + ": Did not retrieve response");
                return null;
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        }
    }

}
